import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server_2 {
    public static void main(String args[]) {
        ServerSocket serverForClient = null;
        Socket socketOnServer = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try {
            serverForClient = new ServerSocket(3001);
        } catch (IOException e1) {
            System.out.println(e1);
        }
        try {
            System.out.println("等待客户呼叫");
            socketOnServer = serverForClient.accept(); //堵塞状态，除非有客户呼叫
            System.out.println("客户已连接");
            out = new DataOutputStream(socketOnServer.getOutputStream());
            in = new DataInputStream(socketOnServer.getInputStream());
            String leng = in.readUTF(); // in读取信息，堵塞状态
            byte ctext[] = new byte[Integer.parseInt(leng)];
            for (int i = 0;i<Integer.parseInt(leng);i++) {
                String temp = in.readUTF();
                ctext[i] = Byte.parseByte(temp);
            }
            // 获取密钥
            FileInputStream f2 = new FileInputStream("keykb1.txt");
            int num2 = f2.available();
            byte[] keykb = new byte[num2];
            f2.read(keykb);
            SecretKeySpec k = new SecretKeySpec(keykb, "DESede");
            // 解密
            Cipher cp = Cipher.getInstance("DESede");
            cp.init(Cipher.DECRYPT_MODE, k);
            byte[] ptext = cp.doFinal(ctext);
            System.out.println("后缀表达式已被解密：");
            for (int i = 0; i < ptext.length; i++) {
                System.out.print(ptext[i] + ",");
            }
            System.out.println("");
            // 显示明文
            String p = new String(ptext, "UTF8");
            System.out.println("服务器收到客户的请求:计算后缀表达式" + p);
            out.writeUTF(MyDC.jisuan(new StringBuffer(p))+"");
        } catch (Exception e) {
            System.out.println("客户已断开" + e);
        }
    }
}
